import Common from '@/utils/Common.js';
import FileUtil from "@/utils/FileUtil.js";
import request from '@/utils/request';
import db from '@/utils/db';
import { upload, uploadImage } from '@/utils/upload';
import eventBus from '@/utils/eventBus.js';
export default {
	methods: {
        convertLocaleCheckSubmited: function(row) {
            var problem = {};
            problem.tid = row.tid;
            problem.id = row.id;
            problem.batchId = row.batch_id;
            problem.bidSectionId = row.bid_section_id;
            problem.buildingId = row.building_id;
            problem.contractorId = row.contractor_id;
            problem.itemId = row.item_id;
            problem.place = row.place;
            problem.problemValues = Common.strToJson(row.problem_values);
            problem.registBy = row.regist_by;
            problem.registDate = new Date(row.regist_date);
            problem.remark = row.remark;
            problem.repairDeadline = new Date(row.repair_deadline);
            problem.reinspectBy = row.reinspect_by;
            problem.reinspectCompletedDate = new Date(row.reinspect_completed_date);
            problem.reinspectImageFile = Common.strToJson(row.reinspect_image_file);
            problem.reinspectRemark = row.reinspect_remark;
            problem.repairBy = row.repair_by;
            problem.repairDate = new Date(row.repair_date);
            problem.repairImageFile = Common.strToJson(row.repair_image_file);
            problem.repairRemark = row.repair_remark;
            problem.problemClassId = row.item_id;
            problem.problemId = row.desc_id;
            problem.status = row.status;
            problem.imageFile = Common.strToJson(row.image_file);
            problem.smallImageFile = Common.strToJson(row.small_image_file);
            problem.roomId = row.room_id;
            problem.ccs =  Common.strToJson(row.ccs);
            problem.closeDate = new Date(row.close_date);
            problem.closeReason = row.close_reason;
            problem.sentBackBy = row.sent_back_by;
            problem.sentBackDate = new Date(row.sent_back_date);
            problem.sentBackImageFile = Common.strToJson(row.sent_back_image_file);
            problem.sentBackRemark = row.sent_back_remark;
            problem.checkqualityRepairId = row.checkquality_repair_id;
            problem.repair = row.repair;
            problem.reinspect = Common.strToJson(row.reinspect);
            problem.checkqualityReinspectId = Common.strToJson(row.checkquality_reinspect_id);
            return problem;
        },
        convertLocaleCheckDraft: function(row) {
            var problem = {};
            problem.tid = row.tid;
            problem.batchId = row.batch_id;
            problem.buildingId = row.building_id;
            problem.unitId = row.unit_id;
            problem.floorId = row.floor_id;
            problem.houseId = row.house_id;
            problem.place = row.place;
            problem.problemClassId = row.problem_class_id;
            problem.problemId = row.problem_id;
            problem.remark = row.remark;
            problem.emergencyDegree = row.emergency_degree;
            problem.repairDeadline = row.repair_deadline;
            problem.regist = row.regist;
            problem.contractorId = row.contractor_id;
            problem.repair = row.repair;
            problem.reinspects = Common.strToJson(row.reinspects);
            problem.ccs = Common.strToJson(row.ccs);
            problem.problemValues = Common.strToJson(row.problem_values);
            problem.photos = Common.strToJson(row.photos);
            problem.imageFile = [];
            problem.photos.forEach(photo => {
            	window.resolveLocalFileSystemURL(photo, fileEntry => {
            		fileEntry.file(file => {
            			problem.imageFile.push({
            				url: file.localURL
            			});
            		});
            	});
            });
            return problem;
        },
        draftRegist: function(tid) {
        	
        },
        problemRegist: function(problem, isDraft) {
            let self = this;
            let element = null;
            let place = null;
            if(isDraft) {
                place = problem.place;
            }else{
                place = self.place;
            }
            this.$f7.dialog.confirm('', '确定提交吗?', function() {
                let dialog = self.$f7.dialog.progress('上传图片中', 0);
                dialog.finishCount = 0;
                let data = {
                	batchId: problem.batchId,
                	buildingId: problem.buildingId,
                	unitId: problem.unitId,
                	floorId: problem.floorId,
                	houseId: problem.houseId,
                	place: place,
                	problemClassId: problem.problemClassId,
                	problemId: problem.problemId,
                	registBy: problem.regist,
                	remark: problem.remark,
                	emergencyDegree: problem.emergencyDegree,
                	days: problem.repairDeadline,
                	contractorId: problem.contractorId,
                	repairs: [problem.repair],
                	reinspects: problem.reinspects,
                	ccs: problem.ccs,
                	problemValues: problem.problemValues,
                	photos: []
                };
                let promises = [];
                problem.photos.forEach(photoPath => {
                	let promise = FileUtil.read(photoPath, 'image/jpeg').then(blob => {
                		let splits = photoPath.split("/");
                		let filename = splits[splits.length - 1];
                		return uploadImage(filename, blob);
                	}).then(result => {
                		data.photos.push({url: result.url});
                		dialog.finishCount++;
                		dialog.setProgress(parseInt(dialog.finishCount / (problem.photos.length + 1)) * 100);
                		return Promise.resolve();
                	});
                	promises.push(promise);
                });
                Promise.all(promises).then(() => {
                	return request({
                		url: '/api/checkQualityProblem/add',
                		method: 'post',
                		data: data
                	});
                }).then(data => {
                	element = data.element;
                	let promises = [];
                	let promise = null;
                	
                	promise = db.insert('tb_checkquality_problem', [element]);
                    promises.push(promise);

                	promise = db.insert('tmp_unprocessed_problem_local_check_unprocessed', [element]);
                    promises.push(promise);
                	
                	promise = request({
                		url: '/api/checkQualityRepair/findByCheckQualityProblemId',
                		method: 'get',
                		params: {
                			checkQualityProblemId: element.id
                		}
                	}).then(data => {
                		let elements = data.list;
                		return db.insert('tb_checkquality_repair', elements);
                	}).catch(error => {
                		console.error(error);
                		return Promise.resolve();
                	});
                	promises.push(promise);
                	
                	promise = request({
                		url: '/api/checkQualityReinspect/findByCheckQualityProblemId',
                		method: 'get',
                		params: {
                			checkQualityProblemId: element.id
                		}
                	}).then(data => {
                		let elements = data.list;
                		return db.insert('tb_checkquality_reinspect', elements);
                	}).catch(error => {
                		console.error(error);
                		return Promise.resolve();
                	});
                	promises.push(promise);
                	
                	return Promise.all(promises);
                }).then(() => {
                	dialog.close();
                    self.$f7.dialog.alert('', '提交问题成功！');
                    if(isDraft) {
                        self.submitedProblem(element.id);
                        self.draftProblemDelete(problem.tid);
                    }else{
                        self.$f7router.emit('submitedProblem', element.id);
                        if(problem.tid != null) {
                            self.$f7router.emit('deleteDraftProblem', problem.tid);
                        }
                        self.$f7router.back();
                    }
                    eventBus.$emit("load-count");
                }).catch(error => {
                	dialog.close();
                    self.$f7.dialog.alert(error.detail.msg, '提交问题失败！');
                    if(!isDraft) {
                        self.saveTemporary();
                    }
                	console.error(error);
                });
            });
        },
	}
}